home *** CD-ROM | disk | FTP | other *** search
- Path: garden.csc.calpoly.edu!not-for-mail
- From: dstubbs@garden.csc.calpoly.edu (Dan Stubbs)
- Newsgroups: comp.lang.c
- Subject: Re: while loop problem
- Date: 12 Mar 1996 16:58:44 -0800
- Organization: Cal Poly, San Luis Obispo
- Message-ID: <4i56k4$n5d@garden.csc.calpoly.edu>
- References: <Pine.OSF.3.91.960312133449.7844B-100000@io.UWinnipeg.ca> <Do6DB0.EtE@microunity.com>
- NNTP-Posting-User: dstubbs@garden.csc.calpoly.edu
-
- In article <Do6DB0.EtE@microunity.com>,
- Tom Sanders <toms@MicroUnity.com> wrote:
- >In article <Pine.OSF.3.91.960312133449.7844B-100000@io.UWinnipeg.ca>, Bill Simpson <wsimpson@uwinnipeg.ca> writes:
- >|> Consider the following code fragment:
- >|>
- >|> y=2000; z=1000;
- >|> x=0;
- >|> while(x<=XMAX)
- >|> {
- >|> x+=(int) erand(mean);
- >|> setdot(x,y,z);
- >|> }
- >|>
- >|> The above code will also attempt to plot one point at an x value >XMAX
- >|> before it terminates.
- >|> Is there a nice way to write the code so it works properly?
- >|>
- >|> The only way I have thought of is
- >|> y=2000; z=1000;
- >|> x=0;
- >|> while(x<=XMAX)
- >|> {
- >|> x+=(int) erand(mean);
- >|> if(x<=XMAX)
- >|> setdot(x,y,z);
- >|> }
- >|>
- >|> which seems very clumsy since the same test is done twice.
- >|>
-
- There are several basic ways to do it. All of them rely on
- computing the first value to plot *before* entering the loop.
- That is, essentially operating like a for loop. In your loop
- x is initialized to 0 and then the 0 is discarded without being
- used. Starting with the first value to plot allows you to
- reverse the innards of the loop and avoid the extra test.
-
- y=2000; z=1000;
- x = (int) erand(mean);
- while(x<=XMAX)
- {
- setdot(x,y,z);
- x+=(int) erand(mean);
- }
-
- or
-
- y=2000; z=1000;
- x = (int) erand(mean);
- for (; x<=XMAX; x = (int) erand(mean))
- setdot(x,y,z);
-
- or (a bit clumsy)
-
- y=2000; z=1000;
- x = (int) erand(mean);
- if (x <= XMAX)
- do {
- setdot(x,y,z);
- x+=(int) erand(mean);
- } while (x <= XMAX)
-
-